<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <span>本月: 发送双份奖金</span>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleClick">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 员工列表 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="" :index="handleIndex" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" sortable="">
            <template v-slot="{row}">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatHireType" /> -->
          <!-- formatter 的作用专门用于控制格式化列的数据  -->
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry |formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template #default="{ row }">
              <el-switch v-model="row.enableState" active-value="1" inactive-value="0" active-color="red" inactive-color="lightgray" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleBox(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :total="total" :current-page="queryParams.page" :page-size="queryParams.size" layout="sizes,prev, pager, next,jumper,->,total" :page-sizes="[2, 5, 8, 10,30,50]" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
        </div>
      </el-card>
    </div>
    <!-- 添加员工 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 分配角色 -->
    <assign-role :show-role-dialog.sync="showRoleDialog" :current-user-id="currentUserId" />
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees.js'
import types from '@/api/constant/employees.js'
import AddEmployee from './components/AddEmployee.vue'
import moment from 'moment'
import AssignRole from './components/AssignRole.vue'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  // 时间过滤器
  filters: {
    formatTime (value) {
      if (!value) return ''
      return moment(value).format('yyyy-MM-DD')
    }
  },
  data () {
    return {
      currentUserId: '',
      showRoleDialog: false,
      // 显示隐藏
      showDialog: false,
      // 聘用形式
      hireType: types.hireType,
      // 列表总数
      total: 0,
      // 员工列表数据
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 2
      }
    }
  },
  computed: {
    handleIndex () {
      return this.queryParams.page * this.queryParams.size - this.queryParams.size + 1
    }
  },
  created () {
    this.loadEmpList()
  },
  methods: {
    // 点击角色按钮，显示弹窗，记录id
    showRoleBox (id) {
      this.currentUserId = id
      this.showRoleDialog = true
      // console.log(id)
    },
    // 把后端返回的员工数据转换为Excel需要的数据
    translateData (list) {
      const result = {
        title: [],
        data: []
      }
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 生成导出表头信息
      // Object.keys(对象) 拿到对象中所有的键
      result.title = Object.keys(headers)
      // 转换原始的员工列表数据
      list.forEach(item => {
        // 每次遍历生成一行数据
        const row = []
        // 生成每一行数据项(列)
        result.title.forEach(tname => {
          // 根据中文的名称 tname 获取英文的名称
          const enKey = headers[tname]
          // 根据英文的key获取对应的属性值
          let value = item[enKey]
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            try {
              value = moment(item[enKey]).format('yyyy-MM-DD')
            } catch {
              value = '无效时间'
            }
          }
          if (enKey === 'formOfEmployment') {
            const info = this.hireType.find(item => parseInt(item.id) === Number(value))
            value = info ? info.value : '其他'
          }
          // 把该该项数据放到row中
          row.push(value)
        })
        // 把每一个员工数据(row)放到二维数组(data)中
        result.data.push(row)
      })

      return result
    },

    // 导出员工信息
    async handleClick () {
      // 导出员工信息
      const ret = await reqGetEmployeeList({ page: 1, size: 100 })
      console.log(ret)
      if (ret.code === 10000) {
        const result = this.translateData(ret.data.rows)
        // console.log(result)
        // import 导入的文件称之为 按需加载
        // 底层webpack规则
        // 在底层打包的时候，会单独打包到一个js文件，网络法请求的时候只请求看到的路由所对应的组件，加载的内容量减少了
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: result.title, // 表头 必填
            data: result.data, // 具体数据 必填
            // 下载的文件名称
            filename: 'excel-list',
            // 是否固定列宽
            autoWidth: true,
            // 文件后缀
            bookType: 'xlsx'
          })
        })
      }
    },

    // 删除
    async handleDelete (id) {
      try {
        const ret = await this.$confirm('确认要删除员工吗？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (ret === 'cancel') return
        const delRet = await reqDelEmployee(id)
        if (delRet.code === 10000) {
          this.$message.success('删除成功')
          this.loadEmpList()
        } else {
          this.$message.error(delRet.message)
        }
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 聘用形式
    formatHireType (type) {
      const info = this.hireType.find(item => parseInt(item.id) === parseInt(type))
      if (info) {
        return info.value
      } else {
        return '其他'
      }
    },
    // 页码变化
    handleCurrentChange (page) {
      this.queryParams.page = page
      this.loadEmpList()
    },
    // 每页条数
    handleSizeChange (size) {
      this.queryParams.size = size
      this.loadEmpList()
    },
    // 获取列表
    async loadEmpList () {
      const ret = await reqGetEmployeeList(this.queryParams)
      // console.log(ret)
      if (ret.code === 10000) {
        this.list = ret.data.rows
        this.total = ret.data.total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
